# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'CID00401': {
        'API_KEY': 'Cj96Gjp4V.sGsx',
        'gateway': 'https://payment.skillfully.com.tw/tpayv3/pay.aspx',
        'query_gateway': 'https://payment.skillfully.com.tw/tpayv3/checkorder.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_order_sign(parameter, key):
    s = '{}&{}&{}&{}&{}&{}:{}'.format(
        parameter['scode'], parameter['orderid'], '%.2f' % (float(parameter['amount'])),
        parameter['currcode'], parameter['paytype'], parameter['noticeurl'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(parameter, key):
    s = '{}&{}:{}'.format(parameter['scode'], parameter['orderid'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'skillfully origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    s = '{}&{}&{}&{}&{}&{}&{}:{}'.format(params['scode'], params['orderno'], params['orderid'],
                                         '%.2f' % (float(params['amount'])),
                                         params['paytype'], params['status'], params['respcode'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("skillfully sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def _get_pay_type(service):
    if service == 'wxpay':
        paytype = 'wechat_h5'
    elif service == 'unionpay2':
        paytype = 'unionpay2'
    elif service == 'quick':
        paytype = 'unionpayq'
    elif service == 'qq':
        paytype = 'qqpay'
    else:
        paytype = 'unionpayq_h5'
    return paytype


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')

    p_dict = OrderedDict((
        ('scode', app_id),
        ('orderid', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('amount', '%.2f' % pay_amount),
        ('productname', 'charge'),
        ('currcode', 'CNY'),
        ('userid', str(pay.id)[-6:]),
        ('noticeurl', '{}/pay/api/{}/skillfully/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    p_dict['sign'] = generate_order_sign(p_dict, key)
    _LOGGER.info(u'skillfully origin data: %s', p_dict)
    html_text = _build_form(p_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("skillfully notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('skillfully event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data.get('orderno')
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('skillfully check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'scode': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    _LOGGER.info(u'skillfully query data: %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info(u'skillfully query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['status'])
        trade_no = data['orderno']
        total_fee = float(data['amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('skillfully query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('skillfully data error, status_code: %s', response.status_code)
